<template>
  <div>
    <head-tab />
    <div class="form-container">
      <el-form :model="formData"
               ref="formData"
               v-loading="loading"
               :rules="rules"
               label-width="120px">
        <el-form-item label="账号："
                      prop="username">
          <span v-if="isEdit === '1'">{{formData.username || '无'}}</span>
          <el-input v-if="isEdit === '0'"
                    v-model="formData.username"
                    placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码："
                      prop="password">
          <span v-if="isEdit === '1'">{{formData.password || '无'}}</span>
          <el-input v-if="isEdit === '0'"
                    type="password"
                    disabled
                    v-model="formData.password"
                    placeholder="请输入密码">
            <el-button slot="append"
                       icon="el-icon-edit"
                       @click="handleDialog">修改密码</el-button>
          </el-input>
        </el-form-item>
        <el-form-item v-permission="['admin']">
          <span slot="label"><span style="color:red">*</span>角色：</span>
          <span v-if="isEdit === '1'">{{formData.role_id || '无'}}</span>
          <el-select v-model="formData.role_id"
                     v-if="isEdit === '0'"
                     :disabled="isAdmin"
                     placeholder="请选择角色">
            <el-option v-for="item in roleOptions"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名："
                      prop="nick_name">
          <span v-if="isEdit === '1'">{{formData.nick_name || '无'}}</span>
          <el-input v-model="formData.nick_name"
                    v-if="isEdit === '0'"
                    placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="渠道："
                      prop="chnl_name">
          <span v-if="isEdit === '1'">{{formData.chnl_name || '无'}}</span>
          <el-input v-model="formData.chnl_name"
                    :disabled="isAdmin"
                    v-if="isEdit === '0'"
                    placeholder="请输入渠道"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="success"
                     v-if="isEdit === '0'"
                     :loading="loading"
                     @click="submit">提交</el-button>
          <el-button type="info"
                     @click="back">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog title="密码编辑"
               :visible.sync="pwdDialog">
      <el-form :model="pwdForm"
               :rules="pwdRules"
               ref="pwdForm"
               status-icon
               label-width="100px">
        <el-form-item label="新密码："
                      prop="pass">
          <el-input type="password"
                    v-model="pwdForm.pass"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码："
                      prop="checkPass">
          <el-input type="password"
                    v-model="pwdForm.checkPass"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="submitForm('pwdForm')">提交</el-button>
          <el-button @click="resetForm('pwdForm')">重置</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from '@/utils/index'
import headTab from '../headTab.vue'
import { register, updateUser, getAllRoles, getUserById } from '@/api/auth'
import { getAllChannel } from '@/api/mng'
export default {
  components: { headTab },
  name: 'UserForm',
  data() {
    const checkPhone = (rule, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (!reg.test(value)) {
        return callback(new Error('手机格式不正确'))
      } else {
        return callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.pwdForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      pwdForm: {},
      pwdRules: {
        pass: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
        checkPass: [{ validator: validatePass, trigger: 'blur' }]
      },
      pwdDialog: false,
      uuid: window.sessionStorage.getItem('uuid'),
      formData: {},
      isEdit: this.$route.query.isEdit,
      id: this.$route.query.id,
      loading: false,
      roleOptions: [],
      chnlOptions: [],
      rules: {
        username: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请填写密码', trigger: 'blur' }],
        role_id: [{ required: true, message: '请选择角色', trigger: 'blur' }],
        nick_name: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请填写手机号', trigger: 'blur' },
        { validator: checkPhone, trigger: 'blur' }],
        chnl_id: [{ required: true, message: '请选择渠道', trigger: 'blur' }],
      }
    }
  },
  computed: {
    handleSelect() {
      if (this.formData.role_id === 1 || this.formData.role_id === 2) {
        this.formData.chnl_id = 0
        return false
      } else {
        return true
      }

    },
    isAdmin() {
      const role = window.sessionStorage.getItem('role')
      if (role === 'admin') {
        return false
      } else {
        return true
      }
    }
  },
  created() {
    if (this.id !== null) {
      this.getInfo()
    }
    this.initRoleData()

  },
  methods: {
    parseTime,
    handleDialog() {
      this.pwdDialog = true
      this.pwdForm = {}
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.formData.password = this.pwdForm.pass
          this.pwdDialog = false
        } else {

          return false;
        }
      });
    },
    resetForm(form) {
      this.$refs[form].resetFields()
    },
    getInfo() {
      const params = {
        uuid: this.uuid,
        user_id: parseInt(this.id)
      }
      this.loading = true
      getUserById(params).then(res => {
        this.formData = res.data.results[0]
        this.formData.role_id = parseInt(res.data.results[0].role_id)

        this.loading = false
      }).catch(e => {
        this.loading = false
      })
    },
    initRoleData() {
      getAllRoles({}).then(res => {
        if (res.publicData.retInfo.retCode === 0) {
          this.roleOptions = res.data.results

        }
      })
    },
    initChnlData() {
      const params = {
        uuid: this.uuid,
        user_id: JSON.parse(window.sessionStorage.getItem('user')).id,
        page: 0,
        size: 50
      }
      getAllChannel(params).then(res => {
        if (res.publicData.retInfo.retType === 0) {
          this.chnlOptions = res.data.results

        }
      })
    },
    submit() {
      this.formData.uuid = this.uuid
      if (this.formData.role_id === null || this.formData.role_id === undefined) {
        this.formData.role_id = 3
      }
      this.$refs['formData'].validate(valid => {
        if (valid) {
          this.loading = true
          // 判断id是否存在，若存在则修改，否则编辑
          if (this.id === null) {
            register(this.formData).then(res => {
              if (res.publicData.retInfo.retType === 0) {
                this.$notify.success('创建成功')
                this.$router.push('/?activeName=3-2')
              } else if (res.publicData.retInfo.retType === 2) {
                this.$notify.error(res.publicData.retInfo.retMsg)
              } else {
                this.$notify.error('创建失败')
              }
              this.loading = false
            }).catch(e => {
              this.$notify.error('接口有误')
              this.loading = false
            })
          } else {
            console.log('update')
            updateUser(this.formData).then(res => {
              if (res.publicData.retInfo.retType === 0) {
                this.$notify.success('更新成功')
                this.$router.push('/?activeName=1')
              } else {
                this.$notify.error('更新失败')
              }
              this.loading = false
            }).catch(e => {
              this.$notify.error('接口有误')
              this.loading = false
            })
          }
        } else {
          return false
        }
      })

    },
    back() {
      this.$router.push({
        path: '/',
        query: { activeName: this.$route.query.activeName }
      })
    }
  },
}
</script>

<style lang="scss" scoped>
</style>